package com.motion.opengles_tutorial;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * http://toughcoder.net/blog/2018/07/31/introduction-to-opengl-es-2-dot-0/
 */
public class FirstDemoActivity extends AppCompatActivity {
    private GLSurfaceView mGLSurfaceView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_first);
        mGLSurfaceView = this.findViewById(R.id.gl_surfaceview);
        mGLSurfaceView.setEGLContextClientVersion(2);
        mGLSurfaceView.setRenderer(mRenderer);
        mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);


    }

    @Override
    protected void onResume() {
        super.onResume();
        mGLSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mGLSurfaceView.onPause();
    }


    private static final GLSurfaceView.Renderer mRenderer = new GLSurfaceView.Renderer() {
        private static final String VERTEX_SHADER =  "void main() {\n" +
                "gl_Position = vec4(0., 0., 0., 1.0);\n" +
                "gl_PointSize = 20.0;\n" +
                "}\n";
        private static final String FRAGMENT_SHADER = "void main(){\n" +
                "gl_FragColor =vec4(1.0,0.0,0.0,1.0);\n" +
                "}\n";
        private int mGLProgram = -1;

        @Override
        public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
            GLES20.glClearColor(0f, 0f, 0f, 1.f);

            int vertex = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
            GLES20.glShaderSource(vertex, VERTEX_SHADER);
            GLES20.glCompileShader(vertex);

            int fragment = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
            GLES20.glShaderSource(fragment, FRAGMENT_SHADER);
            GLES20.glCompileShader(fragment);

            mGLProgram = GLES20.glCreateProgram();
            GLES20.glAttachShader(mGLProgram, vertex);
            GLES20.glAttachShader(mGLProgram, fragment);
            GLES20.glLinkProgram(mGLProgram);

            GLES20.glValidateProgram(mGLProgram);
            int[] result = new int[1];
            GLES20.glGetProgramiv(mGLProgram, GLES20.GL_VALIDATE_STATUS, result, 0);

        }

        @Override
        public void onSurfaceChanged(GL10 gl10, int i, int i1) {
            GLES20.glViewport(0, 0, i, i1);

        }

        @Override
        public void onDrawFrame(GL10 gl10) {
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
            GLES20.glUseProgram(mGLProgram);

            GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 1);
        }
    };

}
